Gotchas Solutions


In [13]:
from sympy import *
init_printing()

For each exercise, fill in the function according to its docstring.

Symbols

What will be the output of the following code?

x = 3
y = symbols('y')
a = x + y
y = 5
print(a)

Replace ??? in the below code with what you think the value of a will be. Remember to define any Symbols you need!


In [14]:
def symbols_exercise():
    """
    >>> def testfunc():
    ...     x = 3
    ...     y = symbols('y')
    ...     a = x + y
    ...     y = 5
    ...     return a
    >>> symbols_exercise() == testfunc()
    True
    """
    y = symbols('y')
    return 3 + y

In [15]:
def testfunc():
    x = 3
    y = symbols('y')
    a = x + y
    y = 5
    return a

symbols_exercise() == testfunc()


Out[15]:
True

Equality

Write a function that takes two expressions as input, and returns a tuple of two booleans. The first if they are equal symbolically, and the second if they are equal mathematically.


In [16]:
def equality_exercise(a, b):
    """
    Determine if a = b symbolically and mathematically.

    Returns a tuple of two booleans. The first is True if a = b symbolically,
    the second is True if a = b mathematically.  Note the second may be False
    but the two still equal if SymPy is not powerful enough.

    Examples
    ========

    >>> x = symbols('x')
    >>> equality_exercise(x, 2)
    (False, False)
    >>> equality_exercise((x + 1)**2, x**2 + 2*x + 1)
    (False, True)
    >>> equality_exercise(2*x, 2*x)
    (True, True)
    """
    return (a == b, simplify(a - b) == 0)

In [17]:
x = symbols('x')

In [18]:
equality_exercise(x, 2)


Out[18]:
(False, False)

In [19]:
equality_exercise((x + 1)**2, x**2 + 2*x + 1)


Out[19]:
(False, True)

In [20]:
equality_exercise(2*x, 2*x)


Out[20]:
(True, True)

^ and /

Correct the following functions


In [21]:
def operator_exercise1():
    """
    >>> operator_exercise1()
    x**2 + 2*x + 1/2
    """
    x = symbols('x')
    return x**2 + 2*x + Rational(1, 2)

In [22]:
operator_exercise1()


Out[22]:
$$x^{2} + 2 x + \frac{1}{2}$$

In [23]:
def operator_exercise2():
    """
    >>> operator_exercise2()
    (x**2/2 + 2*x + 3/4)**(3/2)
    """
    x = symbols('x')
    return (x**2/2 + 2*x + Rational(3, 4))**Rational(3, 2)

In [24]:
operator_exercise2()


Out[24]:
$$\left(\frac{x^{2}}{2} + 2 x + \frac{3}{4}\right)^{\frac{3}{2}}$$

In [ ]: